package org.example.gateway.config;

import org.example.gateway.filter.JwtAuthFilter;
import org.example.gateway.filter.DebugRouteFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.util.Arrays;

@Configuration
public class RouteConfig {

    private final JwtAuthFilter jwtAuthFilter;
    private final DebugRouteFilter debugRouteFilter;
    
    @Value("${websocket-config.listen-service-url}")
    private String listenServiceWebSocketUrl;

    @Autowired
    public RouteConfig(JwtAuthFilter jwtAuthFilter, DebugRouteFilter debugRouteFilter) {
        this.jwtAuthFilter = jwtAuthFilter;
        this.debugRouteFilter = debugRouteFilter;
    }

    // 全局CORS配置
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(Arrays.asList("*"));
        config.setAllowedMethods(Arrays.asList("*"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setMaxAge(30L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        System.out.println("=== 正在配置网关路由 ===");
        
        RouteLocator routeLocator = builder.routes()
                // WebSocket路由，支持ws://协议 - 优先级最高，使用负载均衡
                .route("websocket-route", r -> r
                        .path("/ws/**")
                        .uri("lb://service-listen"))
                        
                // student模块路由，不需要任何校验
                .route("student-route", r -> r
                        .path("/student/**")
                        .filters(f -> f.rewritePath("/student/(?<segment>.*)", "/${segment}"))
                        .uri("lb://service-student"))

                // login模块的login接口路由，不需要任何校验
                .route("login-route", r -> r
                        .path("/user/login")
                        .filters(f -> f.rewritePath("/user/login", "/login"))
                        .uri("lb://service-login"))

                // pay模块路由，不需要任何校验
                .route("pay-route", r -> r
                        .path("/pay/**")
                        .filters(f -> f.rewritePath("/pay/(?<segment>.*)", "/api/pay/${segment}"))
                        .uri("lb://service-pay"))

                // office模块路由，仅JWT校验
                .route("office-route", r -> r
                        .path("/office/**")
                        .filters(f -> f
                                .rewritePath("/office/(?<segment>.*)", "/${segment}")
                                .filter(debugRouteFilter)
                                .filter(jwtAuthFilter))
                        .uri("lb://service-office"))

                // counselor模块路由，仅JWT校验
                .route("counselor-route", r -> r
                        .path("/counselor/**")
                        .filters(f -> f
                                .rewritePath("/counselor/(?<segment>.*)", "/${segment}")
                                .filter(jwtAuthFilter))
                        .uri("lb://service-counselor"))

                // faculty模块路由，仅JWT校验
                .route("faculty-route", r -> r
                        .path("/faculty/**")
                        .filters(f -> f
                                .rewritePath("/faculty/(?<segment>.*)", "/${segment}")
                                .filter(jwtAuthFilter))
                        .uri("lb://service-faculty"))

                // login模块的其他接口路由，只需要JWT校验
                .route("login-other-route", r -> r
                        .path("/user/**")
                        .filters(f -> f
                                .rewritePath("/user/(?<segment>.*)", "/${segment}")
                                .filter(jwtAuthFilter))
                        .uri("lb://service-login"))

                .build();
        
        System.out.println("=== 网关路由配置完成 ===");
        System.out.println("配置的路由数量: " + routeLocator.getRoutes().collectList().block().size());
        System.out.println("路由列表:");
        routeLocator.getRoutes().collectList().block().forEach(route -> {
            System.out.println("  - " + route.getId() + " -> " + route.getUri());
        });
        return routeLocator;
    }
}